package com.nondo.rdp.finance.endpoint.api.admin.setting.course;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.rdp.auth.common.RoleUtils;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.StageCourse;
import com.nondo.rdp.finance.model.course.AdminStageCourseQuery;
import com.nondo.rdp.finance.model.course.StageCourseBean;
import com.nondo.rdp.finance.service.course.CourseGroupService;
import com.nondo.rdp.finance.service.course.CourseService;
import com.nondo.rdp.finance.service.course.StageCourseService;

@RestController("apiAdminStageCourse")
@RequestMapping("/api/admin/stageCourse")
public class StageCourseEndpoint {
    @Autowired
    StageCourseService stageCourseService;
    
    @Autowired
    CourseService courseService;
    
    @Autowired
    CourseGroupService courseGroupService;
    
    /**
     * 查看阶段课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/info/{id}")
	public View info(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") Long id) {
		View<AdminStageCourseQuery> view = new View<AdminStageCourseQuery>(20000, "获取数据成功");
		
		AdminStageCourseQuery stageCourseQuery = new AdminStageCourseQuery();
		
		if (id != null) {
			StageCourse stageCourse = stageCourseService.findOne(id);
			if (stageCourse != null) {
				stageCourseQuery = stageCourseService.getStageCourseQuery(stageCourse);
			}
		}
		
		view.setData(stageCourseQuery);
		return view;
	}
    
    /**
     * 添加阶段课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
	@RequestMapping("/add")
	public View add(HttpServletRequest request, HttpServletResponse response,
			@Validated(StageCourseBean.Add.class) @RequestBody StageCourseBean stageCourse, BindingResult result) {
		View view = new View(20000, "添加成功");

		if (result.hasErrors()) {
			view.setCode(40000);
			view.setMessage(ValidateUtil.first(result.getAllErrors()));
		} else {
			StageCourse stageCourseDb = null;
			String[] cids = stageCourse.getCid().split(",");
			for (String cid : cids ) {
				Course course = courseService.findOne(Long.parseLong(cid));
				stageCourseDb = stageCourseService.getOne(course.getId(), stageCourse.getType());
				if (stageCourseDb == null) {
					stageCourseDb = new StageCourse();
					stageCourseDb.setType(stageCourse.getType());
					//CourseGroup courseGroup = courseGroupService.findOne(stageCourse.getGroupId());
					stageCourseDb.setCourse(course);
					//stageCourseDb.setCourseGroup(courseGroup);
					this.stageCourseService.save(stageCourseDb);
				}
			}
		}
		return view;
	}

    /**
     * 更新阶段课程
     * @param request
     * @param response
     * @param id
     * @return
     */
	@PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
	@RequestMapping("/update")
	public View update(HttpServletRequest request,
			HttpServletResponse response,
			@Validated(StageCourseBean.Update.class) @RequestBody StageCourseBean stageCourse, BindingResult result) {
		View view = new View(20000, "更新成功");

		if (result.hasErrors()) {
			view.setCode(40000);
			view.setMessage(ValidateUtil.first(result.getAllErrors()));
		} else {
			StageCourse stageCourseDb = stageCourseService.findOne(stageCourse.getId());
			Course course = courseService.findOne(Long.parseLong(stageCourse.getCid()));
			stageCourseDb = stageCourseService.getOne(course.getId(), stageCourse.getType());
			if (stageCourseDb != null
					&& stageCourseDb.getId() == stageCourse.getId()) {
				return View.ofError("该课程已存在于此类型的课程列表中");
			} else {
				stageCourseDb = new StageCourse();
				BeanUtils.copy(stageCourse, stageCourseDb);
			}
			//CourseGroup courseGroup = courseGroupService.findOne(stageCourse.getGroupId());
			stageCourseDb.setCourse(course);
			//stageCourseDb.setCourseGroup(courseGroup);
			this.stageCourseService.update(stageCourseDb);
		}

		return view;
	}

    /**
     * 获取阶段课程列表
     * @param request
     * @param response
     * @param query
     * @return
     */
	@PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/list")
    public View<Page<AdminStageCourseQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<StageCourse> query) {
        View<Page<AdminStageCourseQuery>> view = new View<Page<AdminStageCourseQuery>>(20000, "获取列表成功");

        StageCourse stageCourse = query.getData();

        Page<StageCourse> page = stageCourseService.findAll(new Page<StageCourse>(query.getPage(), query.getSize()), stageCourse);
        
        Page<AdminStageCourseQuery> resultPage = page.convertPage(new ConvertCall<StageCourse, Page<AdminStageCourseQuery>>(){

			@Override
			public Page<AdminStageCourseQuery> execute(Page<StageCourse> srcPage) {
				 Page<AdminStageCourseQuery> stageCoursePage = new Page<AdminStageCourseQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
				 List<AdminStageCourseQuery> stageCourseQueryList = new ArrayList<AdminStageCourseQuery>();
				 List<StageCourse> stageCourseList = srcPage.getContent();
				 for(StageCourse stageCourse : stageCourseList){
					 AdminStageCourseQuery stageCourseQuery = stageCourseService.getStageCourseQuery(stageCourse);
					 stageCourseQueryList.add(stageCourseQuery);
				 }
				 stageCoursePage.setContent(stageCourseQueryList);;
				return stageCoursePage;
			}
        	
        });

        view.setData(resultPage);

        return view;
    }

    /**
     * 删除阶段课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");

        this.stageCourseService.delete(id);

        return view;
    }
}